package com.dongjiantong.app.controller.quarantine;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.quarantine.dto.SupervisionRecordDto;
import com.dongjiantong.quarantine.enums.FileType;
import com.dongjiantong.quarantine.model.SupervisionRecords;
import com.dongjiantong.quarantine.serviceImpl.BreedReportsFileReadService;
import com.dongjiantong.quarantine.serviceImpl.SupervisionRecordsReadService;
import com.dongjiantong.quarantine.serviceImpl.SupervisionRecordsSubReadService;
import com.dongjiantong.quarantine.serviceImpl.SupervisionRecordsWriteService;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 26/12/17.
 */
@Slf4j
@OpenBean
public class SupervisionRecordsController {

    @Reference(version = "1.0.0")
    private SupervisionRecordsReadService supervisionRecordsReadService;
    @Reference(version = "1.0.0")
    private SupervisionRecordsWriteService supervisionRecordsWriteService;
    @Reference(version = "1.0.0")
    private SupervisionRecordsSubReadService supervisionRecordsSubReadService;
    @Reference(version = "1.0.0")
    private BreedReportsFileReadService breedReportsFileReadService;

    /**
     * 查询督查的详情
     *
     * @param id 主键id
     * @return Response<SupervisionRecordDto>
     */
    @OpenMethod(
            key = "find.supervision.record.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public Response<SupervisionRecordDto> findById(Long id) {
        if (id == null) {
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(), HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }
        try {
            SupervisionRecords supervisionRecords = supervisionRecordsReadService.findById(id);
            List<Map<String, Object>> supervisionRecordsSubList = supervisionRecordsSubReadService.findBySupervisionId(id);
            Map<String, Object> map = Maps.newHashMap();
            map.put("field", "photo_supervision_list");
            map.put("type1", ReportType.SUPERVISION_RECORD.value());
            map.put("type2", FileType.PHOTO.value());
            map.put("relevanceId", supervisionRecords.getId());
            List<String> photo_supervision_list = breedReportsFileReadService.findListByType(map);
            map.put("field", "video_supervision_list");
            map.put("type2", FileType.VIDEO.value());
            List<String> video_supervision_list = breedReportsFileReadService.findListByType(map);
            map.put("field", "video_photo_supervision_list");
            map.put("type2", FileType.PHOTO.value());
            List<String> video_photo_supervision_list = breedReportsFileReadService.findListByType(map);
            supervisionRecords.setPhoto_supervision_list(photo_supervision_list);
            supervisionRecords.setVideo_supervision_list(video_supervision_list);
            supervisionRecords.setVideo_photo_supervision_list(video_photo_supervision_list);
            SupervisionRecordDto supervisionRecordDto = new SupervisionRecordDto();
            supervisionRecordDto.setSupervisionRecords(supervisionRecords);
            supervisionRecordDto.setMapList(supervisionRecordsSubList);
            return Response.ok(supervisionRecordDto);
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖端的分页查询
     *
     * @param pageNum  页码
     * @param pageSize 条数
     * @param farmId   养殖场ID
     * @param statuses 状态集合
     * @return Response<PageInfo<SupervisionRecords>>
     */
    @OpenMethod(
            key = "paging.supervision.record.for.farm",
            paramNames = {"pageNum", "pageSize", "farmId", "statuses"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<SupervisionRecords>> pagingForFarm(Integer pageNum, Integer pageSize, Long farmId, List<Integer> statuses) {
        if (farmId == null)
            throw new OPServerException(HttpCode.FARM_ID_IS_NOT_EXIST.getCode(), HttpCode.FARM_ID_IS_NOT_EXIST.getMessage());

        try {
            Map<String, Object> map = Maps.newHashMap();
            map.put("farmId", farmId);
            if (statuses != null && !statuses.isEmpty()) map.put("statuses", statuses);
            return Response.ok(supervisionRecordsReadService.pagingForFarm(pageNum, pageSize, map));
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 政府端的分页查询
     *
     * @param pageNum  页码
     * @param pageSize 条数
     * @param farmId   养殖场ID
     * @param statuses 状态集合
     * @return Response<PageInfo<SupervisionRecords>>
     */
    @OpenMethod(
            key = "paging.supervision.record.for.gov.list",
            paramNames = {"pageNum", "pageSize", "farmId", "statuses"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<SupervisionRecords>> pagingForGovList(Integer pageNum, Integer pageSize, Long farmId, List<Integer> statuses) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            List<Long> farmIds = new ArrayList<>();
            if (farmId != null){
                farmIds.add(farmId);
            }else {
                LoginInfo loginInfo = UserUtil.getCurrentUser();
                farmIds = loginInfo.getBreedFactoryIds();
            }
            map.put("farmIds", farmIds);
            if (statuses != null && !statuses.isEmpty()) map.put("statuses", statuses);
            return Response.ok(supervisionRecordsReadService.pagingForGovList(pageNum, pageSize, map));
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 政府端的地图的查询 （按月）
     * @param statuses 状态集合
     * @return Response<List<SupervisionRecordDto>>
     */
    @OpenMethod(
            key = "find.supervision.list.for.gov.map",
            paramNames = {"statuses"},
            httpMethods = RequestMethod.GET
    )
    public Response<List<SupervisionRecordDto>> findListForGovMap(List<Integer> statuses) {
        if (statuses == null) throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(), HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        try{
            Map<String, Object> map = Maps.newHashMap();
            map.put("statuses",statuses);
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            map.put("farmIds",loginInfo.getBreedFactoryIds());
            map.put("deleteFlag",1);
            List<SupervisionRecords> supervisionRecordsList = supervisionRecordsReadService.findListForGovMap(map);
            List<SupervisionRecordDto> supervisionRecordDtoList = new ArrayList<>();
            for (SupervisionRecords supervisionRecords : supervisionRecordsList) {
                SupervisionRecordDto supervisionRecordsDto = new SupervisionRecordDto();
                supervisionRecordsDto.setSupervisionRecords(supervisionRecords);
                Long farm_id = supervisionRecords.getFarm_id();
                map.put("farmId", farm_id);
                List<SupervisionRecords> supervisionRecordsList1 = supervisionRecordsReadService.findListForGovMapByFarmId(map);
                supervisionRecordsDto.setArrayList(supervisionRecordsList1);
                supervisionRecordDtoList.add(supervisionRecordsDto);
            }
            return Response.ok(supervisionRecordDtoList);
        }catch (Exception e){
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 政府端的轨迹list的查询 （按月）
     * @param pageNum 页码
     * @param pageSize 条数
     * @param status 状态
     * @param farmId 养殖场ID
     * @return Response<PageInfo<SupervisionRecords>>
     */
    @OpenMethod(
            key = "paging.supervision.record.for.gov.trace",
            paramNames = {"pageNum","pageSize","status","farmId"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<SupervisionRecords>> pagingForGovTrace(Integer pageNum, Integer pageSize, Integer status,Long farmId){
        try {
            Map<String , Object> map = Maps.newHashMap();
            if (status != null) map.put("status",status);
            List<Long> farmIds = new ArrayList<>();
            if (farmId != null) {
                farmIds.add(farmId);
                map.put("farmIds",farmIds);
            }else {
                LoginInfo loginInfo = UserUtil.getCurrentUser();
                farmIds = loginInfo.getBreedFactoryIds();
            }
            map.put("deleteFlag",1);
            return Response.ok(supervisionRecordsReadService.pagingForGovTrace(pageNum,pageSize,map));
        }catch (Exception e){
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode() , HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * 创建督查单据
     *
     * @param supervisionRecordDto 督查的dto
     * @param toStatus             到状态
     * @return Response<Map<String, Object>> key = id
     */
    @OpenMethod(
            key = "create.supervision.record",
            paramNames = {"supervisionRecordDto", "toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String, Object>> create(SupervisionRecordDto supervisionRecordDto, Integer toStatus) {
        if (supervisionRecordDto == null)
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(), HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        SupervisionRecords supervisionRecords = supervisionRecordDto.getSupervisionRecords();
        if (supervisionRecords == null)
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(), HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        List<Map<String, Object>> supervisionRecordsSubList = supervisionRecordDto.getMapList();
        if (supervisionRecordsSubList == null)
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(), HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        try {
            Date date = new Date();
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            supervisionRecords.setCreated_at(date);
            supervisionRecords.setUpdated_at(date);
            supervisionRecords.setDelete_flag(1);
            return Response.ok(supervisionRecordsWriteService.create(supervisionRecords, supervisionRecordsSubList, toStatus,loginInfo));
        } catch (Exception e) {
            return Response.fail(HttpCode.DATA_CREATE_FAIL.getCode(), HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }


    /**
     * 更新督查单据对象
     *
     * @param supervisionRecordDto 督查dto
     * @param toStatus             到状态
     * @return Response<Map<String, Object>> key = isSuccess
     */
    @OpenMethod(
            key = "update.supervision.record",
            paramNames = {"supervisionRecordDto", "toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String, Object>> update(SupervisionRecordDto supervisionRecordDto, Integer toStatus) {
        if (supervisionRecordDto == null)
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(), HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        SupervisionRecords supervisionRecords = supervisionRecordDto.getSupervisionRecords();
        if (supervisionRecords == null)
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(), HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        List<Map<String, Object>> supervisionRecordsSubList = supervisionRecordDto.getMapList();
        if (supervisionRecordsSubList == null)
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(), HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        if (supervisionRecords.getId() == null)
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(), HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        try {
            Date date = new Date();
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            supervisionRecords.setUpdated_at(date);
            supervisionRecords.setDelete_flag(1);
            Integer currentStatus = supervisionRecordsReadService.findStatusById(supervisionRecords.getId());
            if (currentStatus != null && !currentStatus.equals(supervisionRecords.getStatus()))
                throw new OPServerException(HttpCode.DOCUMENT_REPEAT_SUBMIT.getCode(), HttpCode.DOCUMENT_REPEAT_SUBMIT.getMessage());
            return Response.ok(supervisionRecordsWriteService.update(supervisionRecords, supervisionRecordsSubList, toStatus,loginInfo));
        } catch (Exception e) {
            return Response.fail(HttpCode.DATA_UPDATE_FAIL.getCode(), HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }
}
